package jui.business
{
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.utils.Dictionary;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;
 	
	public class ManagersFactory extends EventDispatcher
	{
		
		private var managersDictionary: Dictionary = new Dictionary(true); 
				
		public function getManager(managerClassId: String): Object //IJUIManager
		{
			var requestedManagerInstance: IJUIManager = managersDictionary[managerClassId];
			
			if( requestedManagerInstance == null )
			{
				var ClassReference: Class = getDefinitionByName(managerClassId) as Class;
			
				//trace("Create manager: " + getQualifiedClassName( ClassReference ) );
			
				requestedManagerInstance = new ClassReference();
				
				// Add new manager to dictionary
				managersDictionary[managerClassId] = requestedManagerInstance;
			}
			else
			{
				trace("Return existing manager: " + getQualifiedClassName( requestedManagerInstance ) );
			}
			
			return requestedManagerInstance;			
		}
		
		public static function getInstance(): ManagersFactory
		{
			if (__instance == null) 
			{
				allowInstantiation = true;
				__instance = new ManagersFactory();
				allowInstantiation = false;
			}
			return __instance;
		}
		
		public function ManagersFactory(target:IEventDispatcher=null)
		{
			if(!allowInstantiation)
			{
				throw new Error("Error: The constructor is disabled in Singleton. Use getInstance method instead.");
			}
		}
		
		private static var __instance: ManagersFactory;
		private static var allowInstantiation: Boolean;
	}
}
